<template>
  <j-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk()"
    @cancel="handleCancel"
    cancelText="关闭">
    <template slot='footer'>
      <a-button @click='handleCancel'>取消</a-button>
      <a-button v-if='!disableSubmit' type='primary' @click='handleOk'>确认</a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <a-divider orientation='left' style='font-weight: 500;margin-top: 0px;'>基础信息</a-divider>
      <a-form :form="form">
        <a-col :md='12' :sm='24'>
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="规则名称">
            <a-input v-decorator="['signConfigName',validatorRules.signConfigName ]" :disabled='disableSubmit' placeholder='' />
          </a-form-item>
        </a-col>
<!--        <a-col :md='12' :sm='24'>-->
<!--          <a-form-item-->
<!--            :labelCol="labelCol"-->
<!--            :wrapperCol="wrapperCol"-->
<!--            label="规则类型">-->
<!--            <cn-dict-select-tag v-decorator="['signConfigType',validatorRules.signConfigType]"-->
<!--                                :disabled="disableSubmit" :triggerChange="true"-->
<!--                                dictCode="sign_config_type" placeholder="请选择规则类型"/>-->
<!--          </a-form-item>-->
<!--        </a-col>-->
      </a-form>
      <a-divider orientation='left' style='font-weight: 500;margin-top: 0px;'>考勤规则</a-divider>
      <a-form :form="form">
        <a-col :md='24' :sm='24'>
        <a-form-item
          :labelCol="{
          xs: { span: 24,},
          sm: { span: 3 ,},
        }"
          :wrapperCol="{
          xs: { span: 28 ,},
          sm: { span: 16 },
        }"
          label="签到时间">
          <a-time-picker v-decorator="[ 'signInStart', validatorRules.signInStart]" :disabled="disableSubmit" format="HH:mm:ss" valueFormat="HH:mm:ss" />
          <span> ~ </span>
          <a-time-picker v-decorator="[ 'signInEnd', validatorRules.signInEnd]" :disabled="disableSubmit" format="HH:mm:ss" valueFormat="HH:mm:ss" />
        </a-form-item>
        </a-col>

        <a-form-item
          :labelCol="{
          xs: { span: 24,},
          sm: { span: 3 ,},
        }"
          :wrapperCol="wrapperCol"
          label="签退时间">
          <a-time-picker v-decorator="[ 'signOutStart', validatorRules.signOutStart]" :disabled="disableSubmit" format="HH:mm:ss" valueFormat="HH:mm:ss" />
          <span> ~ </span>
          <a-time-picker v-decorator="[ 'signOutEnd', validatorRules.signOutEnd]" :disabled="disableSubmit" format="HH:mm:ss" valueFormat="HH:mm:ss" />
        </a-form-item>
        <a-form-item :labelCol="{
          xs: { span: 24,},
          sm: { span: 3 ,},
        }" :wrapperCol="{
          xs: { span: 24 ,},
          sm: { span: 10 }
        }" label="组织名称">
            <j-tree-select v-decorator="['signOrgCode', validatorRules.signOrgCode]" :disabled="disableSubmit" data-type="org"
                           placeholder="请选择所属组织" style="width: 85%" @change="handleDepartCode" permflag="sign_config_add_org" />
          </a-form-item>
        <a-form-item :labelCol="{
          xs: { span: 24,},
          sm: { span: 3 ,},
        }" :wrapperCol="{
          xs: { span: 24 ,},
          sm: { span: 9 },
        }" label="电子围栏">
          <cn-dict-select-tag  v-decorator="['electronicFence']"
                              :disabled="disableSubmit" :triggerChange="true"
                              dictCode="electronic_fence" />
        </a-form-item>
      </a-form>
      <a-divider orientation='left' style='font-weight: 500;margin-top: 0px;'>打卡地点</a-divider>
      <a-button v-if='!disableSubmit' style='margin: 10px 30px 0px 30px;' type='primary'
                @click='handleConfigTer'>新增
      </a-button>
      <div style='padding: 10px 20px;'>
        <a-table ref='table' :columns='columns2' :dataSource='dataSource'
                 :rowSelection='{selectedRowKeys:selectedRowKeys, onChange: onSelectChange2}'
                 :scroll='{x:400,y:240 }' bordered
                 rowKey='id' size='middle'
                 @change='handleTableChange'>
            <span v-if='!disableSubmit' slot='action' slot-scope='text, record'>
              <a style='color: red;' @click='handleDelete(record)'>删除</a>
            </span>
        </a-table>
      </div>
    </a-spin>
    <punch-in-place-modal ref='punchModal' :dataSource='dataSource' @ok='punchModalOK'></punch-in-place-modal>
  </j-modal>
</template>

<script>
  import { httpAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import VcTimePicker from 'ant-design-vue/es/vc-time-picker/TimePicker'
  import ARangePicker from 'ant-design-vue/es/date-picker/RangePicker'
  import JTreeSelect from '@/components/cn-form/JTreeSelect'
  import PunchInPlaceModal from './PunchInPlaceModal'
  export default {
    name: 'SfaSignConfigModal',
    components: { ARangePicker, VcTimePicker,JTreeSelect,PunchInPlaceModal},
    data () {
      return {
        disableSubmit:false,
        title:"操作",
        visible: false,
        model: {},
        labelCol: {
          xs: { span: 24,},
          sm: { span: 5 ,},
        },
        wrapperCol: {
          xs: { span: 24 ,},
          sm: { span: 16 },
        },
        confirmLoading: false,
        form: this.$form.createForm(this),
        validatorRules:{
          signConfigName:{
            //规则名称
            rules: [{
              required: true, message: '', trigger: 'submit'
            }]
          },
          electronicFence:{
            rules: [{
              required: true, message: '', trigger: 'submit'
            }]
          },
          signConfigType:{
            rules: [{
              required: true, message: '', trigger: 'submit'
            }]
          },
          signInStart: {
            rules: [{
              required: true, message: '', trigger: 'submit'
            }]
          },
          signInEnd: {
            rules: [{
              required: true, message: '', trigger: 'submit'
            }]
          },
          signOutStart: {
            rules: [{
              required: true, message: '', trigger: 'submit'
            }]
          },
          signOutEnd: {
            rules: [{
              required: true, message: '', trigger: 'submit'
            }]
          },
          signOrgCode: {
            rules: [{
              required: true, message: ''
            }]
          },
          status: {
            rules: [{
              required: true, message: ''
            }]
          }
        },
        url: {
          add: window._CONFIG['domianSfaURL']+"/signConfig/saveOrUpdate",
        },
        dataSource: [],
        /* table选中keys*/
        selectedRowKeys: [],
        /* table选中records*/
        selectionRows: [],
        //经销商
        columns2: [
          {
            title: '地址',
            align: 'center',
            dataIndex: 'address'
          },
          {
            title: '打卡类型',
            align: 'center',
            dataIndex: 'dataTypeStr'
          },
          {
            title: '范围',
            align: 'center',
            dataIndex: 'distance'
          },
          {
            title: '操作',
            dataIndex: 'action',
            fixed: 'right',
            align: 'center',
            width: 150,
            scopedSlots: {
              customRender: 'action'
            }
          }
        ],
      }
    },
    methods: {
      //新增打卡地点
      handleConfigTer() {
        this.$refs.punchModal.visible = true
        this.$refs.punchModal.dataSource = this.dataSource

      },
      //经销商
      onSelectChange1(selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectionRows = selectionRows
      },
      //删除
      handleDelete(e) {
        let key = this.dataSource.map(item => {
          return item.id
        })
        this.dataSource.splice(key.indexOf(e.id), 1)
      },
      punchModalOK(e){
        this.dataSource.push(e)
      },
      //添加请求参数，组织改变时，改变请求参数
      handleDepartCode(value, name) {
        console.log(name)
        this.model.departCode = ''
        this.model.departName = name
      },
      add () {
        this.visible = true;
        this.disableSubmit = false
      },
      edit (record) {
        console.log(record)
        this.form.resetFields();
        this.model = Object.assign({}, record);
        console.log(this.initialValue)
        this.visible = true;
        if(this.model.addressVoList != null){
          this.dataSource = this.model.addressVoList
          for(let i =0;i<this.dataSource.length;i++){
            if(this.dataSource[i].dataType === 1){
              this.dataSource[i].dataTypeStr = '上班签到'
            }
            if(this.dataSource[i].dataType === 2){
              this.dataSource[i].dataTypeStr = '下班签退'
            }
            if(this.dataSource[i].dataType === 3) {
              this.dataSource[i].dataTypeStr = '上下班打卡'
            }
          }
        }else {
          this.dataSource = []
        }
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,'signConfigName','signOrgName','signOrgCode','signOutEnd','signOutStart','addressVoList',
          'signInEnd','signInStart','signConfigType','electronicFence'))
        });
      },
      close () {
        this.$emit('close');
        this.visible = false;
        this.dataSource =[]
        this.form.resetFields();
      },
      handleOk () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            let httpurl = '';
            httpurl += this.url.add;
            let method = '';
            method = 'post';
            let formData = Object.assign(this.model, values);
            console.log(formData.departCode)
            formData.signOrgName = formData.departName
            formData.addressVoList = this.dataSource||[]
            if(formData.electronicFence&&formData.addressVoList.length==0){
              this.$message.error('请新增打卡地点')
              return
            }
            that.confirmLoading = true;
            //时间格式化
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
                that.close();
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
        })
      },
      handleCancel () {
        this.close()
      },
    }
  }
</script>

<style scoped>

</style>